/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.storebank.web;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.storebank.service.StoreBankService;
import com.jeeplus.modules.storebank.entity.StoreBank;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.store.entity.Store;
import com.jeeplus.modules.store.service.StoreService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;

/**
 * 厂家银行卡Controller
 * @author lixinapp
 * @version 2019-10-14
 */
@Controller
@RequestMapping(value = "${adminPath}/storebank/storebank")
public class StoreBankController extends BaseController {

	@Autowired
	private StoreBankService storebankService;
	@Autowired
	private StoreService storeService;

	@ModelAttribute
	public StoreBank get(@RequestParam(required=false) String id) {
		StoreBank entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = storebankService.get(id);
		}
		if (entity == null){
			entity = new StoreBank();
		}
		return entity;
	}
	
	/**
	 * 厂家提现列表页面
	 */
	@RequiresPermissions("storebank:storebank:list")
	@RequestMapping(value = {"list", ""})
	public String list(StoreBank storebank, Model model) {
		model.addAttribute("storebank", storebank);
		return "modules/storebank/storebankList";
	}
	
		/**
	 * 厂家提现列表数据
	 */
	@ResponseBody
	@RequiresPermissions("storebank:storebank:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(StoreBank storebank, HttpServletRequest request, HttpServletResponse response, Model model) {
		// 判断当前登录用户
		User user = UserUtils.getUser();
		if (user.isShop()) {
			storebank.setDataScope(" AND store.user_id = '"+user.getId()+"' ");
		}
		Page<StoreBank> page = storebankService.findPage(new Page<StoreBank>(request, response), storebank); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑厂家提现表单页面
	 */
	@RequiresPermissions(value={"storebank:storebank:view","storebank:storebank:add","storebank:storebank:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(StoreBank storebank, Model model) {
		// 判断当前登录用户
		User user = UserUtils.getUser();
		if (user.isShop()) {
			Store store = storeService.findUniqueByProperty("user_id", user.getId());
		}
		model.addAttribute("storebank", storebank);
		return "modules/storebank/storebankForm";
	}
	/**
	 * 保存厂家店铺账单
	 */
	@ResponseBody
	@RequiresPermissions(value={"storebank:storebank:add","storebank:storebank:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(StoreBank storebank, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		User user = UserUtils.getUser();
		if (user.isShop()) {
			Store store = storeService.findUniqueByProperty("user_id", user.getId());
			storebank.setStore(store);
		}
		storebank.setCreateDate(new Date());
		if(StringUtils.isBlank(storebank.getState())){
			storebank.setState("0");
		}
		if("0".equals(storebank.getState())){
			storebankService.executeUpdateSql("UPDATE t_store_bank SET state = '1' WHERE store_id = '" + storebank.getStore().getId()+ "'");
		}
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(storebank);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		storebankService.save(storebank);//保存
		j.setSuccess(true);
		j.setMsg("保存厂家银行卡成功");
		return j;
	}
	/**
	 * 启用银行卡
	 */
	@ResponseBody
	@RequiresPermissions(value="storebank:storebank:edit")
	@RequestMapping(value = "audit")
	public AjaxJson audit(StoreBank storebank, String type) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!"1".equals(storebank.getState())) {
			j.setSuccess(false);
			j.setMsg("只能操作待启用的申请");
			return j;
		}
		if("0".equals(type)){
			storebankService.executeUpdateSql("UPDATE t_store_bank SET state = '1' WHERE store_id = '" + storebank.getStore().getId()+ "'");
		}
		storebank.setState(type);
		storebankService.save(storebank);
		j.setSuccess(true);
		j.setMsg("审核厂家提现成功");
		return j;
	}
	/**
	 * 批量删除厂家提现
	 */
	@ResponseBody
	@RequiresPermissions("storebank:storebank:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			storebankService.delete(storebankService.get(id));
		}
		j.setMsg("删除厂家提现成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("storebank:storebank:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(StoreBank storebank, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "厂家提现"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<StoreBank> page = storebankService.findPage(new Page<StoreBank>(request, response, -1), storebank);
    		new ExportExcel("厂家提现", StoreBank.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出厂家提现记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("storebank:storebank:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<StoreBank> list = ei.getDataList(StoreBank.class);
			for (StoreBank storebank : list){
				try{
					storebankService.save(storebank);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条厂家提现记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条厂家提现记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入厂家提现失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入厂家提现数据模板
	 */
	@ResponseBody
	@RequiresPermissions("storebank:storebank:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "厂家提现数据导入模板.xlsx";
    		List<StoreBank> list = Lists.newArrayList(); 
    		new ExportExcel("厂家提现数据", StoreBank.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }

}